package com.rfid;

import android.os.Handler;

import com.rfid.sockethelper.ClientManager;
import com.rfid.sockethelper.SocketBase;
import com.rfid.udp.UdpListener;
import com.rfid.udp.UdpManager;

import java.net.SocketException;

public class TcpConnectManager implements SocketBase.OnReceiveListener {

    boolean release;
    boolean udpMode;
    Handler mHandler = new Handler();
    SocketBase.OnReceiveListener mOnReceiveListener;

    public void connect(String ip) {
        udpMode = false;
        ClientManager.getManager().addListener(this);
        ClientManager.getManager().postConnect(ip);
    }

    public void updConnect() throws SocketException {
        udpMode = true;
        UdpManager.getInstance().listening(new UdpListener() {
            @Override
            public void onReceived(String message, String phoneInfo, String ip) {
                if (ClientManager.getManager().getClient(ip) != null) {
                    return;
                }
                ClientManager.getManager().postConnect(ip);
            }
        });
    }

    public void setListener(SocketBase.OnReceiveListener listener) {
        mOnReceiveListener = listener;
    }

    @Override
    public void onReceived(String ip, short cmd, CharSequence... text) {
        if (mOnReceiveListener != null) {
            mOnReceiveListener.onReceived(ip,cmd,text);
        }
    }

    @Override
    public void onConnect(final String ip, boolean connect) {
        if (!connect && !udpMode && !release) {
            mHandler.removeMessages(0);
            mHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    ClientManager.getManager().postConnect(ip);
                }
            },2000);
        }
    }
}
